/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.primitives.unix;

import java.util.Map;

import fr.x9c.cadmium.kernel.Block;
import fr.x9c.cadmium.kernel.CodeRunner;
import fr.x9c.cadmium.kernel.Primitive;
import fr.x9c.cadmium.kernel.PrimitiveProvider;
import fr.x9c.cadmium.kernel.Value;

/**
 * This class provides implementation for 'unix_environment' primitive.
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
@PrimitiveProvider
public final class Envir {

    /**
     * No instance of this class.
     */
    private Envir() {
    } // end empty constructor

    /**
     * Returns the environment as an array of string. <br/>
     * Each string has the following format: <i>name<tt>=</tt>value</i>.
     * @param ctxt context
     * @param unit ignored
     * @return the environement as a string array
     */
    @Primitive
    public static Value unix_environment(final CodeRunner ctxt,
                                         final Value unit) {
        final Map<String, String> env = System.getenv();
        final int sz = env.size();
        if (sz > 0) {
            final Block res = Block.createBlock(sz, 0);
            int i = 0;
            for (Map.Entry<String, String> e : env.entrySet()) {
                res.set(i++,
                        Value.createFromBlock(Block.createString(e.getKey() + "=" + e.getValue())));
            } // end for
            return Value.createFromBlock(res);
        } else {
            return ctxt.getContext().getAtom(0);
        } // end if/else
    } // end method 'unix_environment(CodeRunner, Value)'

} // end class 'Envir'
